/*
 * 上海毕冉信息技术有限公司 版权所有
 */
package util.play;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.MDC;
import play.Logger;
import play.mvc.Http;

/**
 * 时间跟踪器.
 */
public class TimeTracker {

    private static final ThreadLocal<Long> _entryTimePoint = new ThreadLocal<>();

    public static void startTrack() {
        //生成日志跟踪ID.
        String ttid = RandomStringUtils.randomAlphanumeric(8);
        MDC.put("ttid", ttid);
        _entryTimePoint.set(System.currentTimeMillis());
    }

    private static void cleanTrack() {
        _entryTimePoint.remove();
        Object objTtid = MDC.get("ttid");
        Http.Response currentResponse = Http.Response.current();
        if (objTtid != null && currentResponse != null) {
            String ttid = String.valueOf(objTtid);
            currentResponse.setHeader("TraceId", ttid);
        }
        MDC.remove("ttid");
    }

    private static Long getEntryTimeMillis() {
        Long entryTime = _entryTimePoint.get();
        if (entryTime == null) {
            return System.currentTimeMillis();
        }
        return entryTime;
    }

    /**
     * 检查是否超过指定毫秒数.
     */
    public static void printTimeOutTrack() {
        Long timeout = getTimeOut();
        String actionName = "sys";
        if (Http.Request.current() != null) {
            actionName = Http.Request.current().action;
        }
        if (timeout > 5000L) {
            Logger.warn("TimeTrack: 慢闪电指数★★★★★--> %s 耗时:%s ms",
                    actionName, timeout);
        } else if (timeout > 2100L) {
            Logger.warn("TimeTrack: 慢闪电指数★★★★---> %s 耗时:%s ms",
                    actionName, timeout);
        } else if (timeout > 1000L) {
            Logger.warn("TimeTrack: 慢闪电指数★★★----> %s 耗时:%s ms",
                    actionName, timeout);
        } else if (timeout > 500L) {
            Logger.warn("TimeTrack: 慢闪电指数★★-----> %s 耗时:%s ms",
                    actionName, timeout);
        } else if (timeout > 200L) {
            Logger.warn("TimeTrack: 慢闪电指数★------> %s 耗时:%s ms",
                    actionName, timeout);
        } else {
            Logger.info("TimeTrack: 耗时:%s ms -> %s",
                    timeout, actionName);
        }
        cleanTrack();
    }

    public static Long getTimeOut() {
        return System.currentTimeMillis() - getEntryTimeMillis();
    }

}
